import pattern from '@/utils/pattern';
import { useRequestHandle } from '@/utils/utils';
import ProForm, { ProFormSwitch, ProFormText } from '@ant-design/pro-form';
import { useUpdateEffect } from '@umijs/hooks';
import { Form,  Modal, Select, Spin, TreeSelect } from 'antd';
import { useRef, useState } from 'react';
import {

  getOrganizationTreeSelectData,
  getRoleTreeSelectData,
  getTreeSelectData,
} from '../service';

const SaveForm = (props) => {
  const { modalVisible, onCancel, onSubmit, loading, record } = props;
  const [positionTree, setPositionTree] = useState([]);
  const [isOldUser, setIsOldUser] = useState(false);
  const [isUpdate, setIsUpdate] = useState(false);
  const formRef = useRef();

  const getTreeSelectHandler = useRequestHandle(getTreeSelectData, (data) => {
    setPositionTree(data);
  });
  const [roleSelectData, setRoleSelectData] = useState([]);
  const getRoleSelectHandler = useRequestHandle(getRoleTreeSelectData, (data) => {
    setRoleSelectData(data);
  });
  const [orgSelectData, setOrgSelectData] = useState([]);
  const getOrgSelectHandler = useRequestHandle(getOrganizationTreeSelectData, (data) => {
    setOrgSelectData(data);
  });
  

  useUpdateEffect(() => {
    if (modalVisible) {
      getTreeSelectHandler.run({});
      getRoleSelectHandler.run({});
      getOrgSelectHandler.run({});
    }
  }, [modalVisible]);
  return (
    <Modal
      destroyOnClose
      title={record.id ? '修改用户' : '新增用户'}
      open={modalVisible}
      onCancel={() => {
        setIsOldUser(false);
        setIsUpdate(false);
        onCancel();
      }}
      width="690px"
      footer={null}
    >
      <Spin tip="正在处理..." spinning={loading}>
        <ProForm
          formRef={formRef}
          onFinish={async (value) => {
            const params = value;
            params.id = record.id;
            params.userName = params.phoneNumber;
            await onSubmit(value);
            setIsOldUser(false);
            setIsUpdate(false);
          }}
          initialValues={{ status: true, ...record }}
        >
          <ProForm.Group>
            <ProFormText
              name="phoneNumber"
              label="手机号"
              disabled={isUpdate || record.id}
              fieldProps={{
                onChange: (e) => {
                  if (e.target.value.length > 11) {
                    formRef.current.setFieldValue('phoneNumber', e.target.value.substring(0, 11));
                  }
                 
                },
              }}
              rules={[
                {
                  required: true,
                  message: '请先输入手机号(长度为11位)',
                  len: 11,
                  pattern: pattern.mobile,
                },
              ]}
            />

            <ProFormText
              name="realName"
              label="真实姓名"
              fieldProps={{
                allowClear: true,
              }}
              disabled={isOldUser}
              placeholder="请输入真实姓名称"
              rules={[{ required: true, message: '请输入真实姓名！' }]}
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormText
              name="password"
              label="登陆密码"
              placeholder={isUpdate || record.id ? '不填则使用原密码！' : '请输入初始密码'}
              rules={[
                {
                  required: !(isUpdate || record.id),
                  message: isUpdate || record.id ? '不填则使用原密码！' : '请先初始密码',
                },
              ]}
            />

            <Form.Item name="roleIds" label="角色" placeholder="请选择角色">
              <Select
                style={{ width: '180px' }}
                mode="multiple"
                allowClear={true}
                disabled={record.userType === 2}
                optionFilterProp="label"
                placeholder="用户拥有的角色"
                options={roleSelectData}
              />
            </Form.Item>
          </ProForm.Group>
          <Form.Item name="positionIds" label="职位" placeholder="请选择职位">
            <TreeSelect
              allowClear={true}
              style={{ width: '100%' }}
              treeNodeFilterProp="title"
              multiple={true}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={positionTree}
              placeholder="用户拥有的职位"
              treeDefaultExpandAll
            />
          </Form.Item>

          <Form.Item name="organizationIds" label="组织架构" placeholder="请选择组织架构">
            <TreeSelect
              allowClear={true}
              style={{ width: '100%' }}
              treeNodeFilterProp="title"
              multiple={true}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={orgSelectData}
              placeholder="用户属于的组织架构"
              treeDefaultExpandAll
            />
          </Form.Item>
        
          {!record.id && (
            <ProFormSwitch
              name="status"
              label="状态"
              checkedChildren="启用"
              unCheckedChildren="禁用"
            />
          )}
        </ProForm>
      </Spin>
    </Modal>
  );
};

export default SaveForm;
